import http from "./http";

import localforage from "localforage";

/**
 * 本地临时缓存
 */
const dbtemp = localforage.createInstance({
  name: "yn-temp"
});

/**
 * 本地永久缓存
 */
const localdb = localforage.createInstance({
  name: "yn-forever"
});

// 每日打开清空临时缓存
dbtemp.clear();

//全网必读
export async function getBooks(option) {
  const url = "/client/queryMustReadNews.htm";
  const def = {
    limit: 25
  };
  const params = Object.assign(def, option);
  return http.get(url, { params });
}

//客户端首页新闻
export async function getHomePage(option) {
  const url = "/client/getHomePage.htm";
  const def = {
    limit: 20
  };
  const params = Object.assign(def, option);
  return http.get(url, { params });
}

//财经日历
export async function getCalendar(params) {
  const url = "/client/financeCalendar.htm";
  const { timeStamp, type } = params;
  const key = timeStamp + "-" + type;
  const cache = await localdb.getItem(key);
  return (
    cache ||
    http.get(url, { params }).then(data => {
      localdb.setItem(key, data);
      return data;
    })
  );
}

//新股中心
export async function getStock(params) {
  const url = "/client/newStockCenter.htm";
  const key = `getStock-${params.type}`;
  const cache = await dbtemp.getItem(key);
  return (
    cache ||
    http.get(url, { params }).then(data => {
      dbtemp.setItem(key, data);
      return data;
    })
  );
}
